package com.example.demo.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.Date;

/**
 * token生成与解析
 */
public class TokenUtil {
    public static final long EXPIRE = 1000 * 60 * 60 * 24; //token过期时间   24小时
    public static final String APP_SECRET = "$2a$10$cBNdP3o0YlBLi44eEWZzquXJ.GmmD4LUB3axPaCwmeX4bwSR3Rr3q";  //密钥 71515xp BCryptPasswordEncoder加密


    /**
     * 生成token
     * @param username
     * @return JwtToken
     */
    public static String getJwtToken(String username){
        String token = Jwts.builder()
                .setHeaderParam("typ", "JWT") // 头参数
                .setSubject("server")  //签发者
                .setIssuedAt(new Date()) //签发时间
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .claim("username", username) //用户账号
                .signWith(SignatureAlgorithm.HS256, APP_SECRET) //加密算法 秘钥
                .compact();

        return token;
    }

    /**
     * 从请求头中获取token
     * @param request
     */
    public static String getToken(HttpServletRequest request) {
        return request.getHeader("token");
    }

    /**
     * 验证token有效性
     * @return
     */
    public static boolean checkToken(String token){
        if(token == null){
            return false;
        }
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(token);

        if(CheckUtil.checkObject(claimsJws)){
            return false;
        }else {
            return true;
        }
    }

    /**
     * 从请求头中解析出username
     * @param request
     * @return
     */
    public static String getTokenUsername(HttpServletRequest request){
        String token = getToken(request);
        if(CheckUtil.checkObject(token)){
            return null;
        }
        Jws<Claims> claimsJws = null;
        try {
            claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(token);
        } catch (Exception e){
            System.out.println("token解析失败");
        }

        String username = null;
        try {
            username = (String) claimsJws.getBody().get("username");
        } catch (NullPointerException e) {
            return username;
        }
        return username;
    }

}
